package com.example.imageswitcher

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.ImageSwitcher
import android.widget.ImageView
import android.widget.ViewSwitcher

class MainActivity : AppCompatActivity() {
    private var downX: Float = 0.0f
    private var upX: Float = 0.0f
    private var index: Int = 1
    private val imageArr:Array<Int> = arrayOf(R.drawable.cat_100,R.drawable.cat_101,R.drawable.cat_102,R.drawable.cat_106)


    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val imageSwitcher = findViewById<ImageSwitcher>(R.id.image_switcher)
        //设置退出动画
        imageSwitcher.outAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_out)
        imageSwitcher.inAnimation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in)

        imageSwitcher.setFactory(ViewSwitcher.ViewFactory {
            val imageView = ImageView(this)
            //设置初始图片
            imageView.setImageResource(imageArr[index])
            imageView
        })

        //左右滑动切换图片
        imageSwitcher.setOnTouchListener { view: View, motionEvent: MotionEvent ->
            //向下滑
            if (motionEvent.action == MotionEvent.ACTION_DOWN) {
                downX = motionEvent.x
                return@setOnTouchListener true
            } else if (motionEvent.action == MotionEvent.ACTION_UP) { //向上滑
                 upX = motionEvent.x
                if (upX.minus(downX) > 100) {
                    //向左滑动
                    index = if (index == 0) 0 else index.dec()
                    imageSwitcher.inAnimation = AnimationUtils.loadAnimation(this,R.anim.slide_in_left)
                    imageSwitcher.outAnimation = AnimationUtils.loadAnimation(this,R.anim.slide_out_right)
                    imageSwitcher.setImageResource(imageArr[index])
                }else if (downX.minus(upX) > 100){
                  //向右滑动
                    index = if (index == imageArr.size - 1) imageArr.size - 1 else index.inc()
                    imageSwitcher.inAnimation = AnimationUtils.loadAnimation(this,R.anim.slide_in_right)
                    imageSwitcher.outAnimation = AnimationUtils.loadAnimation(this,R.anim.slide_out_left)
                    imageSwitcher.setImageResource(imageArr[index])
                }
                return@setOnTouchListener true
            }
            return@setOnTouchListener false
        }

    }
}
